const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const appConfig = require('../conf')
const app = express();
const session = require('express-session')
const fs = require('fs');
const multipart = require('connect-multiparty')
module.exports = {

    //初始化 设置公共中间件

    init: function (app) {
        // 设置模板引擎
        app.set('views', path.join(__dirname, '/../', 'views'));
        app.set('view engine', 'ejs');

        // 设置静态资源
        app.use(express.static(path.join(__dirname, '/../', 'public')));
        app.use(express.json());
        app.use(express.urlencoded({ extended: false }));
        app.use(cookieParser());
        app.use(logger('dev'));
        // session
        app.use(session(appConfig.session));
        // 文件接收插件
        app.use( multipart() );
        
    },

    // 项目启动
    run: function (app) {
        this.init(app)
        app.use(this.routes)
        require('../routes/index')(app)
    },

    // 路由引导
    routes: function (req, res, next) {
        if (!appConfig['modules'][req.hostname]) {
            req.moduleName = 'api'
        } else {
            req.moduleName = appConfig['modules'][req.hostname];
        }


        //验证模块是否存在

        let checkM = fs.existsSync(path.join(__dirname, '/../', `app/${req.moduleName}`))
        if (!checkM) {

            throw new Error('Module does not exist')
        }

        next();
    }
}